$(function() {

	var doc = $(document),
		body = $('body'),
		topMenu = body.find(".top-menu");
		
	doc.on('fileopened', function (e, file) {
		loadFileAsText(file);
	});
		
	var saveFile = function (content, fileName) {
		var textFileAsBlob = new Blob([content], {type:'text/plain'});
		var fileNameToSaveAs = fileName;

		var downloadLink = document.createElement("a");
		downloadLink.download = fileNameToSaveAs;
		downloadLink.innerHTML = "Download File";
		// Firefox requires the link to be added to the DOM
		// before it can be clicked.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
		$(downloadLink).on('click', function () {
			$(downloadLink).remove();
		});
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);

		downloadLink.click();
	}
	
	var loadFileAsText = function (file) {
		var fileToLoad = file,
			fileReader = new FileReader();
			
		fileReader.onload = function(fileLoadedEvent) {
			var textFromFileLoaded = fileLoadedEvent.target.result;
			mainTextArea.val(textFromFileLoaded);
		};
		
		fileReader.readAsText(fileToLoad, "UTF-8");
	}
	
	$.widget("MQM.menuButtons", {

		_create: function () {
			var self = this;
			
			self.initializeButtons();
		},
	
		initializeButtons: function () {
			var self = this,
				open = function () {
					fileInput.click();
				},
				save = function () {
					var position = {
						left: body.find('.save-button')[0].offsetLeft,
						top: body.find('.top-menu').height() + 2
					};
					
					var exportHtml = $('<div></div>');
					dialogue(exportHtml, position);
					
					exportHtml.exportdialogue();
				};
				
			self.addButton('Open', open, 'GFX/Open.gif', 'open-button');
			self.addButton('Save', save, 'GFX/Save.gif', 'save-button');
		},
		
		addButton: function (label, action, img, cls) {
			var self = this,
				e = self.element,
				data = {img: img, label: label},
				button = template("top-menu-button-tmpl", data).appendTo(e);
			
			button.on('click', function () {
				doc.trigger('closedialogue');
			});
			button.on('click', action);
			
			button.addClass(cls);
		}
		
	});	
	
	var dialogue = function (html, position) {
		var dialogue = $('<div></div>').appendTo(body);
		dialogue.dialogue({
			html: html,
			position: position
		});
	};
	
	$.widget("MQM.dialogue", {
	
		options: {
			html: null,
			position: null
		},

		_create: function () {
			var self = this,
				e = self.element;
				o = self.options;
				
			e.html(o.html);
			e.addClass('dialogue');
			e.css({
				top: o.position.top-3,
				left: o.position.left
			});
			
			doc.on('closedialogue', function () {
				e.fadeOut(130 , function () {
					e.remove();
				});
			});
		}
		
	});
	
	$.widget("MQM.exportdialogue", {
		_create: function () {
			var self = this,
				e = self.element;
				
			e.html(template("export-dialogue-tmpl"));
			
			var filename = e.find('.file-name'),
				numQuestions = e.find('.num-questions');
			
			self.okayButton = e.find('.okay').on('click', function () {
				doc.trigger('closedialogue');
				var t = mainTextArea.val();
				t = t.replace(/\s+/g, '');
				if (t === '' || t.indexOf(',') == -1) {
					alert('Invalid Input String\nYou dont have a comma or there is no data.');
					return;
				}
				var arrays = parser.parseQuestions();
				console.log('in index', parseInt(numQuestions.val(), 10));
				var bank = parser.writeQuiz(arrays.qtext, arrays.atext, parseInt(numQuestions.val(), 10));
				saveFile(bank.valueOf(), filename.val() + '.xml');
			});
			
			self.cancelButton = e.find('.cancel').on('click', function () {
				doc.trigger('closedialogue');
			});
		}
	});
	
	$(topMenu).menuButtons();
	$(window).resize();
});